<template>
  <div id="welcome" class="welcome-container">
    <!-- 面包导航 -->
    <el-breadcrumb separator="/" style="padding: 15px 20px; font-size: 14px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据中心</el-breadcrumb-item>
      <el-breadcrumb-item>运营统计</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主要内容区 -->
    <el-row :gutter="20" style="padding: 0 20px 20px">
      <!-- 左侧主统计区 -->
      <el-col :span="16">
        <!-- 关键数据指标卡片 -->
        <el-row :gutter="20" style="margin-bottom: 20px">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-label">总订单数</div>
                <el-statistic
                  :value="totalOrders"
                  :precision="0"
                  class="stat-value"
                >
                  <template #prefix>
                    <el-icon class="stat-icon"
                      ><i class="el-icon-shopping-cart"></i
                    ></el-icon>
                  </template>
                </el-statistic>
                <div class="stat-trend up">
                  <el-icon><i class="el-icon-arrow-up"></i></el-icon>
                  <span>12.5%</span>
                  <span class="trend-text">较上月</span>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-label">今日订单</div>
                <el-statistic
                  :value="todayOrders"
                  :precision="0"
                  class="stat-value"
                >
                  <template #prefix>
                    <el-icon class="stat-icon"
                      ><i class="el-icon-clock"></i
                    ></el-icon>
                  </template>
                </el-statistic>
                <div class="stat-trend up">
                  <el-icon><i class="el-icon-arrow-up"></i></el-icon>
                  <span>8.2%</span>
                  <span class="trend-text">较昨日</span>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-label">总用户数</div>
                <el-statistic
                  :value="totalUsers"
                  :precision="0"
                  class="stat-value"
                >
                  <template #prefix>
                    <el-icon class="stat-icon"
                      ><i class="el-icon-user"></i
                    ></el-icon>
                  </template>
                </el-statistic>
                <div class="stat-trend up">
                  <el-icon><i class="el-icon-arrow-up"></i></el-icon>
                  <span>15.3%</span>
                  <span class="trend-text">较上月</span>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-label">今日新增用户</div>
                <el-statistic
                  :value="todayNewUsers"
                  :precision="0"
                  class="stat-value"
                >
                  <template #prefix>
                    <el-icon class="stat-icon"
                      ><i class="el-icon-user-plus"></i
                    ></el-icon>
                  </template>
                </el-statistic>
                <div class="stat-trend down">
                  <el-icon><i class="el-icon-arrow-down"></i></el-icon>
                  <span>3.1%</span>
                  <span class="trend-text">较昨日</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 订单趋势图表 -->
        <el-card class="chart-card" style="margin-bottom: 20px">
          <div slot="header" class="chart-header">
            <span>订单趋势统计</span>
            <el-select
              v-model="orderTimeRange"
              size="mini"
              @change="handleOrderRangeChange"
            >
              <el-option label="近7天" value="7" />
              <el-option label="近30天" value="30" />
              <el-option label="近90天" value="90" />
            </el-select>
          </div>
          <div class="chart-container">
            <div id="orderTrendChart" class="chart" ref="orderTrendChart"></div>
          </div>
        </el-card>

        <!-- 订单状态分布 -->
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>订单状态分布</span>
            <span class="chart-desc">基于近30天数据</span>
          </div>
          <div class="chart-container">
            <div
              id="orderStatusChart"
              class="chart"
              ref="orderStatusChart"
            ></div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧辅助统计区 -->
      <el-col :span="8">
        <!-- 新用户增长 -->
        <el-card class="chart-card" style="margin-bottom: 20px">
          <div slot="header" class="chart-header">
            <span>新用户增长趋势</span>
            <el-select
              v-model="userTimeRange"
              size="mini"
              @change="handleUserRangeChange"
            >
              <el-option label="近7天" value="7" />
              <el-option label="近30天" value="30" />
            </el-select>
          </div>
          <div class="chart-container">
            <div id="userGrowthChart" class="chart" ref="userGrowthChart"></div>
          </div>
        </el-card>

        <!-- 最近订单列表 -->
        <el-card class="list-card" style="margin-bottom: 20px">
          <div slot="header" class="chart-header">
            <span>最近订单</span>
            <el-button size="mini" type="text">查看全部</el-button>
          </div>
          <el-table :data="recentOrders" border size="mini" style="width: 100%">
            <el-table-column prop="orderNo" label="订单号" width="120" />
            <el-table-column prop="product" label="商品" />
            <el-table-column prop="status" label="状态" width="90">
              <template #default="scope">
                <el-tag
                  :type="
                    scope.row.status === '已完成'
                      ? 'success'
                      : scope.row.status === '待处理'
                      ? 'warning'
                      : 'danger'
                  "
                  size="mini"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="80" />
          </el-table>
        </el-card>

        <!-- 日历组件 -->
        <el-card class="calendar-card">
          <div slot="header" class="chart-header">
            <span>数据日历</span>
            <el-button size="mini" type="text">添加日程</el-button>
          </div>
          <div class="calendar-container">
            <el-calendar>
              <template slot="dateCell" slot-scope="{ date, data }">
                <p
                  :class="[
                    data.isSelected ? 'is-selected' : '',
                    data.day.split('-').slice(2)[0] === today ? 'today' : '',
                  ]"
                >
                  {{ data.day.split("-").slice(2)[0] }}
                  <span
                    v-if="getOrderCountByDate(data.day)"
                    class="date-marker"
                  >
                    {{ getOrderCountByDate(data.day) }}
                  </span>
                </p>
              </template>
            </el-calendar>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import echarts from "echarts";

export default {
  data() {
    return {
      // 统计数据
      totalOrders: 12560,
      todayOrders: 238,
      totalUsers: 52380,
      todayNewUsers: 156,

      // 时间范围选择
      orderTimeRange: "7",
      userTimeRange: "7",

      // 图表实例
      orderTrendChart: null,
      orderStatusChart: null,
      userGrowthChart: null,

      // 订单趋势数据（近7天）
      orderTrendData: {
        dates: ["10/1", "10/2", "10/3", "10/4", "10/5", "10/6", "10/7"],
        orders: [180, 210, 195, 230, 245, 220, 238],
        amounts: [25600, 29800, 27500, 32400, 35600, 31200, 33500],
      },

      // 订单状态分布
      orderStatusData: {
        status: ["已完成", "待处理", "已取消", "退款中"],
        counts: [6500, 2000, 1200, 860],
        colors: ["#52c41a", "#faad14", "#f5222d", "#1890ff"],
      },

      // 用户增长数据（近7天）
      userGrowthData: {
        dates: ["10/1", "10/2", "10/3", "10/4", "10/5", "10/6", "10/7"],
        newUsers: [120, 135, 110, 145, 160, 140, 156],
      },

      // 最近订单列表
      recentOrders: [
        {
          orderNo: "ORD2305678",
          product: "智能手表",
          status: "已完成",
          amount: 1299,
        },
        {
          orderNo: "ORD2305677",
          product: "无线耳机",
          status: "待处理",
          amount: 899,
        },
        {
          orderNo: "ORD2305676",
          product: "笔记本电脑",
          status: "已完成",
          amount: 5999,
        },
        {
          orderNo: "ORD2305675",
          product: "蓝牙音箱",
          status: "已取消",
          amount: 399,
        },
        {
          orderNo: "ORD2305674",
          product: "智能手环",
          status: "已完成",
          amount: 299,
        },
      ],

      // 日历订单标记
      dateOrderCounts: {
        "2023-10-01": 5,
        "2023-10-03": 8,
        "2023-10-05": 12,
        "2023-10-07": 15,
      },

      today: new Date().getDate().toString(),
    };
  },
  methods: {
    // 初始化图表
    initCharts() {
      this.initOrderTrendChart();
      this.initOrderStatusChart();
      this.initUserGrowthChart();
    },

    // 订单趋势图表
    initOrderTrendChart() {
      this.orderTrendChart = echarts.init(this.$refs.orderTrendChart);
      this.updateOrderTrendChart();
    },

    // 更新订单趋势图表
    updateOrderTrendChart() {
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: { color: "#333" },
          formatter: function (params) {
            return `
              <div style="font-weight: bold">${params[0].name}</div>
              <div>订单数: ${params[0].value}</div>
              <div>销售额: ¥${params[1].value.toLocaleString()}</div>
            `;
          },
        },
        legend: {
          data: ["订单数", "销售额"],
          top: 0,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.orderTrendData.dates,
          axisLine: { lineStyle: { color: "#eee" } },
        },
        yAxis: [
          {
            type: "value",
            name: "订单数",
            axisLine: { lineStyle: { color: "#faad14" } },
            splitLine: { lineStyle: { color: "#f5f5f5" } },
          },
          {
            type: "value",
            name: "销售额",
            axisLine: { lineStyle: { color: "#52c41a" } },
            splitLine: { show: false },
            axisLabel: { formatter: "¥{value}" },
          },
        ],
        series: [
          {
            name: "订单数",
            type: "bar",
            data: this.orderTrendData.orders,
            itemStyle: { color: "#faad14" },
            barWidth: "40%",
          },
          {
            name: "销售额",
            type: "line",
            data: this.orderTrendData.amounts,
            yAxisIndex: 1,
            itemStyle: { color: "#52c41a" },
            lineStyle: { color: "#52c41a" },
            symbol: "circle",
            symbolSize: 6,
          },
        ],
      };
      this.orderTrendChart.setOption(option);
    },

    // 订单状态图表
    initOrderStatusChart() {
      this.orderStatusChart = echarts.init(this.$refs.orderStatusChart);
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: { color: "#333" },
        },
        legend: {
          orient: "vertical",
          left: 10,
          data: this.orderStatusData.status,
        },
        series: [
          {
            name: "订单状态",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 6,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: this.orderStatusData.status.map((status, index) => ({
              name: status,
              value: this.orderStatusData.counts[index],
              itemStyle: { color: this.orderStatusData.colors[index] },
            })),
          },
        ],
      };
      this.orderStatusChart.setOption(option);
    },

    // 用户增长图表
    initUserGrowthChart() {
      this.userGrowthChart = echarts.init(this.$refs.userGrowthChart);
      this.updateUserGrowthChart();
    },

    // 更新用户增长图表
    updateUserGrowthChart() {
      const option = {
        tooltip: {
          trigger: "axis",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#eee",
          borderWidth: 1,
          textStyle: { color: "#333" },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.userGrowthData.dates,
          axisLine: { lineStyle: { color: "#eee" } },
        },
        yAxis: {
          type: "value",
          axisLine: { lineStyle: { color: "#1890ff" } },
          splitLine: { lineStyle: { color: "#f5f5f5" } },
        },
        series: [
          {
            name: "新增用户",
            type: "bar",
            data: this.userGrowthData.newUsers,
            itemStyle: { color: "#1890ff" },
            barWidth: "40%",
            emphasis: {
              itemStyle: { color: "#40a9ff" },
            },
          },
        ],
      };
      this.userGrowthChart.setOption(option);
    },

    // 处理订单时间范围变化
    handleOrderRangeChange(value) {
      // 实际项目中可根据value更新数据，这里用死数据演示
      this.updateOrderTrendChart();
    },

    // 处理用户时间范围变化
    handleUserRangeChange(value) {
      // 实际项目中可根据value更新数据，这里用死数据演示
      this.updateUserGrowthChart();
    },

    // 获取日期对应的订单数
    getOrderCountByDate(date) {
      return this.dateOrderCounts[date] || 0;
    },
  },
  mounted() {
    this.initCharts();

    // 监听窗口大小变化，重绘图表
    window.addEventListener("resize", () => {
      this.orderTrendChart && this.orderTrendChart.resize();
      this.orderStatusChart && this.orderStatusChart.resize();
      this.userGrowthChart && this.userGrowthChart.resize();
    });
  },
  beforeDestroy() {
    // 销毁图表实例，避免内存泄漏
    this.orderTrendChart && this.orderTrendChart.dispose();
    this.orderStatusChart && this.orderStatusChart.dispose();
    this.userGrowthChart && this.userGrowthChart.dispose();
    window.removeEventListener("resize", () => {});
  },
};
</script>

<style scoped>
.welcome-container {
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 统计卡片样式 */
.stat-card {
  transition: all 0.3s ease;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.stat-item {
  padding: 15px;
}

.stat-label {
  color: #8c8c8c;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-icon {
  color: #1890ff;
  margin-right: 5px;
  font-size: 18px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
}

.stat-trend.up {
  color: #52c41a;
}

.stat-trend.down {
  color: #f5222d;
}

.trend-text {
  color: #8c8c8c;
  margin-left: 5px;
}

/* 图表卡片样式 */
.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.chart-desc {
  font-size: 12px;
  color: #8c8c8c;
}

.chart-container {
  padding: 15px;
}

.chart {
  width: 100%;
  height: 280px;
}

/* 列表卡片样式 */
.list-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 日历样式 */
.calendar-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.calendar-container {
  padding: 15px;
}

.el-calendar {
  width: 100%;
}

.el-calendar-day {
  height: 60px !important;
}

.is-selected {
  color: #1890ff;
  font-weight: bold;
}

.today {
  color: #f5222d;
  font-weight: bold;
}

.date-marker {
  display: inline-block;
  background-color: #1890ff;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  font-size: 10px;
  line-height: 16px;
  text-align: center;
  margin-left: 3px;
}
</style>
